package com.mf.controller.queue;

import com.mf.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lmf
 * @Create: 2025/5/19 20:24
 * @module  阻塞队列 -数组（队列常用的读写示例在这）
 */
@RestController
@RequestMapping("/ArrayBlockingQueue")
public class ArrayBlockingQueueUse {

    @Operation(summary = "写入Add(队列满了写入抛出异常)")
    @GetMapping("arrAdd")
    public Result<String> arrAdd() {
        // 创建一个容量为2的队列
        final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(2);
        // 添加数据
        queue.add("1");
        queue.add("2");
        queue.add("3");
        return Result.success("add");
    }

    @Operation(summary = "写入offer(队列满了返回false)")
    @GetMapping("arrOffer")
    public Result<Boolean> arrOffer() {
        // 创建一个容量为2的队列
        final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(2);
        // 添加数据
        queue.offer("1");
        queue.offer("2");
        return Result.success(queue.offer("3"));
    }

    @Operation(summary = "写入offer+时间单位(队列满了等待指定时长后加入不了返回false)")
    @GetMapping("arrOfferAndUnit")
    public Result<Boolean> arrOfferAndUnit() throws InterruptedException {
        // 创建一个容量为2的队列
        final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(2);
        // 添加数据
        queue.offer("1", 1, TimeUnit.SECONDS);
        queue.offer("2", 1, TimeUnit.SECONDS);
        return Result.success(queue.offer("3", 1, TimeUnit.SECONDS));
    }

    @Operation(summary = "写入put(等待直到写入成功)")
    @GetMapping("put")
    public Result<Boolean> put() throws InterruptedException {
        // 创建一个容量为2的队列
        final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(2);
        // 添加数据
        queue.put("1");
        queue.put("2");
        queue.put("3");
        return Result.success();
    }
    @Operation(summary = "读方法-也是对应4总【remove,poll,poll+单位,take】对应上手写的四种")
    @GetMapping("read")
    public Result<Boolean> read() throws InterruptedException {
        return Result.success(true);
    }

}
